import App from "../btoolkit/framework/App";
import BButton from "../btoolkit/components/BButton";
import Drag from "../btoolkit/Drag";
import StorageUtils from "../btoolkit/StorageUtils";

const { ccclass, property } = cc._decorator;

const KEY_IS_PROP_LOCKED = 'KEY_IS_PROP_LOCKED';

@ccclass
export default class PropLock extends cc.Component {

    target: cc.Node;
    lockIcon: cc.Node;

    /** 执行锁定 */
    static lock(target: cc.Node, width = 80, offset: cc.Vec2 = cc.Vec2.ZERO) {
        Drag.setLock(target, true);
        let propLock = target.getComponent(PropLock);
        if (!propLock) {
            propLock = target.addComponent(PropLock);
            propLock.target = target;
            propLock.lockIcon = new cc.Node('LockIcon');
            propLock.lockIcon.setParent(target);
            propLock.lockIcon.position = offset;
            let sprite: cc.Sprite = propLock.lockIcon.addComponent(cc.Sprite);
            sprite.spriteFrame = (App.instance.resPreloader.getRes('textures/common/common') as cc.SpriteAtlas).getSpriteFrame('suo11');
            propLock.lockIcon.width = width;
            propLock.lockIcon.height = width * 121 / 108;
        }
    }

    /** 执行解锁 */
    static unlock(target: cc.Node) {
        StorageUtils.saveBool(this.getKey(target), true);
        Drag.setLock(target, false);
        let propLock = target.getComponent(PropLock);
        if (propLock) {
            propLock.destroy();
        }
    }

    /** 但钱是否是锁定状态 */
    static isTargetUnlocked(target: cc.Node) {
        return StorageUtils.readBool(this.getKey(target));
    }

    /** 但钱是否是锁定状态 */
    static isTargetLocking(target: cc.Node) {
        return target.getComponent(PropLock);
    }

    private static getKey(target: cc.Node) {
        return KEY_IS_PROP_LOCKED + '_' + target.parent.name + '_' + target.name;
    }

    onDestroy() {
        Drag.setLock(this.target, false);
        if (this.lockIcon) {
            this.lockIcon.destroy();
        }
    }

}
